package cn.zdm.demo2.auth.service.impl;

import cn.zdm.demo2.auth.constant.FileImportEnum;
import cn.zdm.demo2.auth.mapper.IosAppAuthPoMapper;
import cn.zdm.demo2.auth.model.dto.IosAuthExportDTO;
import cn.zdm.demo2.auth.model.dto.IosAuthImportDTO;
import cn.zdm.demo2.auth.model.po.IosAppAuthPO;
import cn.zdm.demo2.auth.service.FileOptService;
import cn.zdm.demo2.auth.service.IosAppAuthService;
import cn.zdm.demo2.auth.util.FileUtil;
import cn.zdm.demo2.auth.util.RedisUtil;
import cn.zdm.demo2.common.result.ResultObject;
import cn.zdm.demo2.common.result.ResultResponse;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * copyright (C), 2021, 武大吉奥科技有限公司
 *
 * @Program demo2
 * @Description
 * @Author ZhaoDeman
 * @Create 2021/2/3 10:53
 * @Version 1.0.0
 * <author>                <time>                  <version>                   <description>
 * ZhaoDeman        2021/2/3 10:53                 1.0
 */
@Service
public class FileOptServiceImpl implements FileOptService {

    /**
     * auth mapper
     */
    @Autowired
    private IosAppAuthPoMapper iosAppAuthPoMapper;

    /**
     * auth service 集合
     */
    @Autowired
    private IosAppAuthService iosAppAuthService;

    /**
     * redis
     */
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 数据导出文件
     *
     * @param iosAuthExportDTO 传输dto
     * @return
     */
    @Override
    public void export(IosAuthExportDTO iosAuthExportDTO) {
        List<IosAppAuthPO> appAuthPoList = iosAppAuthPoMapper.selectBatchIds(iosAuthExportDTO.getAuthList());
        if (appAuthPoList == null || appAuthPoList.isEmpty()) {
            return;
        }
        String content = JSON.toJSONString(appAuthPoList);
        String fileName = UUID.randomUUID().toString();
        FileUtil.getInstance().downloadFile(iosAuthExportDTO.getRequest(), iosAuthExportDTO.getResponse(), fileName, content);
    }

    /**
     * @param iosAuthImportDTO 导入文件
     * @return
     */
    @Override
    @Transactional
    public ResultObject<Object> importFile(IosAuthImportDTO iosAuthImportDTO) {
        if (StringUtils.isEmpty(iosAuthImportDTO.getDataKey()) && iosAuthImportDTO.getMultipartFile() == null) {
            return ResultResponse.error("请上传文件");
        }
        String fileContent = "";
        MultipartFile file = iosAuthImportDTO.getMultipartFile();
        if (file != null) {
            fileContent = FileUtil.getInstance().readFile(file);
        } else {
            fileContent = (String) redisUtil.get(iosAuthImportDTO.getDataKey());
        }
        if (fileContent.equals("") || fileContent == null) {
            return ResultResponse.error("文件数据为空");
        }
        List<IosAppAuthPO> importAuthList = JSON.parseArray(fileContent, IosAppAuthPO.class);
        if (importAuthList.isEmpty() || importAuthList == null) {
            return ResultResponse.error("文件数据为空");
        }
        //导入
        if (file != null) {
            List<String> authIdList = importAuthList.stream().map(IosAppAuthPO::getId).collect(Collectors.toList());
            List<IosAppAuthPO> exitAuthList = iosAppAuthPoMapper.selectBatchIds(authIdList);
            if (exitAuthList.size() > 0 && exitAuthList != null) {
                String fileKey = UUID.randomUUID().toString();
                redisUtil.set(fileKey, JSON.toJSONString(authIdList), 300);
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("一下数据存在重复");
                exitAuthList.forEach(exitAuth -> {
                    stringBuffer.append(exitAuth.getAuthName()).append("(").append(exitAuth.getId()).append(");");
                });
                HashMap<String, String> resData = new HashMap<>(1);
                resData.put("fileKey", fileKey);
                return ResultResponse.error("存在重复数据" + stringBuffer.toString(), resData);
            }
        }
        return importFile(importAuthList, iosAuthImportDTO.getImportParam()) == true ? ResultResponse.success("导入成功") : ResultResponse.error("导入失败");
    }

    /**
     * @param importAuthList 导入list 集合
     * @param importParam    覆盖还是部分导入
     * @return
     */
    private boolean importFile(List<IosAppAuthPO> importAuthList, String importParam) {
        List<String> authIdList = importAuthList.stream().map(IosAppAuthPO::getId).collect(Collectors.toList());
        List<IosAppAuthPO> exitAuthList = iosAppAuthPoMapper.selectBatchIds(authIdList);
        boolean exitAdjust = exitAuthList != null && !exitAuthList.isEmpty();
        if (exitAdjust && importParam.equals(FileImportEnum.IMPORT_ALL)) {
            //先删除后增加
            List<String> exitAuthIdList = exitAuthList.stream().map(IosAppAuthPO::getId).collect(Collectors.toList());
            iosAppAuthPoMapper.deleteBatchIds(exitAuthIdList);
            iosAppAuthService.saveBatch(importAuthList);
            return true;
        }
        if (!exitAdjust && importAuthList.equals(FileImportEnum.IMPORT_ALL)) {
            iosAppAuthService.saveBatch(importAuthList);
            return true;
        }
        importAuthList = importAuthList.stream().filter(iosAuth -> !exitAuthList.stream().map(IosAppAuthPO::getId).collect(Collectors.toList()).equals(iosAuth.getId())).collect(Collectors.toList());
        if (importAuthList != null && importAuthList.size() > 0) {
            iosAppAuthService.saveBatch(importAuthList);
            return true;
        }
        return false;
    }
}
